//
//  EVSearchBar.m
//  EVClub
//
//  Created by Sam on 13-03-19.
//  Copyright (c) 2013 xunlei.com. All rights reserved.
//

#import "EVSearchBar.h"
#import "UIDevice+EV.h"
#import "UIImage+EV.h"
#import "UIView+EV.h"

@interface EVSearchBar (){
    
    IBOutlet UIView *_searchView;
    IBOutlet UILabel *_placeHolder;
    IBOutlet UILabel *_alertMessageLabel;
    IBOutlet UIImageView *_backgroundView;
    IBOutlet UIImageView *_searchIcon;
    
    IBOutlet UIButton *_cancelButton;
    
    NSInteger _gap;
}
/**
 *  搜索框右侧label，用于显示结果数量（由resultCount决定是否显示，resultCount = -1时不显示）
 */
@property (nonatomic, strong) UILabel *resultCountLabel;
@property (weak, nonatomic) IBOutlet UILabel *lbTopicLogo;//搜索话题时使用

- (IBAction)cancelButtonAction:(id)sender;

@end


@implementation EVSearchBar

+ (EVSearchBar* )loadSearBarWithFrame:(CGRect)frame{
    return [self loadSearBarWithFrame:frame style:SearchStyleNone];
}

+ (EVSearchBar *)loadSearBarWithFrame:(CGRect)frame style:(SearchStyle)style{
    
    EVSearchBar *searchBar = (EVSearchBar*)[UIView ev_viewWithNib:@"EVSearchBar" owner:nil];
    searchBar.frame = frame;
    searchBar.autoShowCancelButton = YES;
    
    switch (style) {
        case SearchStyleGray:{
            [searchBar grayStyle];
        }
            break;
            case SearchStyleBlue:
            [searchBar blueStyle];
            break;
        case SearchStyleWhite:
        case SearchStyleNone:
        default:{
            [searchBar whiteStyle];
        }
            break;
    }
    
    return searchBar;
}

- (void)awakeFromNib {
    [super awakeFromNib];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textFieldTextDidChange:) name:UITextFieldTextDidChangeNotification object:_textField];
    
    if ([UIDevice ev_isIPad]) {
        _gap = 10;
    }
    else{
        _gap = 7;
    }
    
    [self textChecking];
    self.autoresizingMask = UIViewAutoresizingNone;
    [_searchIcon addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapOnSearchIcon:)]];
}

- (void)setUseForTopicSeach:(BOOL)useForTopicSeach {
    _useForTopicSeach = useForTopicSeach;
    _searchIcon.hidden = useForTopicSeach;
    _lbTopicLogo.hidden = !useForTopicSeach;
}

- (void)whiteStyle{
    
    UIImage *bgImage = [UIImage ev_resizeableImageNamed:@"search_bar_frame_white"];
    [_backgroundView setImage:bgImage];
    [_searchIcon setImage:[UIImage imageNamed:@"search_bar_icon_gray"]];
    [_cancelButton setTitle:@"取消" forState:UIControlStateNormal];
}

- (void)grayStyle{
    
    UIImage *bgImage = [UIImage ev_resizeableImageNamed:@"search_bar_frame_gray"];
    [_backgroundView setImage:bgImage];
    [_searchIcon setImage:[UIImage imageNamed:@"search_bar_icon_gray"]];
    [_cancelButton setTitle:@"取消" forState:UIControlStateNormal];
}

- (void)blueStyle{
    
    UIImage *bgImage = [UIImage ev_resizeableImageNamed:@"search_bar_frame_white"];
    [_backgroundView setImage:bgImage];
    [_searchIcon setImage:[UIImage imageNamed:@"search_bar_icon_gray"]];
    [_cancelButton setTitle:@"取消" forState:UIControlStateNormal];
}

-(void)setBackgroundImage:(UIImage *)backgroundImage
{
    _backgroundView.image = backgroundImage;
}

-(UIImage *)backgroundImage
{
    return _backgroundView.image;
}

- (void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect
{
    // Drawing code
}
*/

#pragma mark - buttonAction

- (void)tapOnSearchIcon:(UITapGestureRecognizer *)gesture {
    if (self.delegate && [self.delegate respondsToSelector:@selector(searchBarOnIcon:)]) {
        [self.delegate searchBarOnIcon:self];
    }
}


- (IBAction)cancelButtonAction:(id)sender{
    
    [self showCancelButton:NO];
    if (self.text.length == 0)
    {
        [_alertMessageLabel setHidden:YES];
        [_placeHolder setHidden:NO];
    }
    [self.textField resignFirstResponder];
    if (self.delegate && [self.delegate respondsToSelector:@selector(searchBarCancelButtonClicked:)])
    {
        [self.delegate searchBarCancelButtonClicked:self];
    }
}

#pragma mark - UITextFieldDelegate
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
    if (textField.text.length == 0)
    {
        [_alertMessageLabel setHidden:YES];
        [_placeHolder setHidden:NO];
    }
    if (self.autoShowCancelButton) {
        [self showCancelButton:YES animated:NO];
    }
    if ([self.delegate respondsToSelector:@selector(searchBarShouldBeginEditingTextField:)])
    {
       return [self.delegate searchBarShouldBeginEditingTextField:self];
    }
    return YES;
}

-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    if (self.maxLength) {
        NSInteger length = textField.text.length - range.length + string.length;
        if (length > self.maxLength) {
            return NO;
        }
    }
    return YES;
}

- (void)textFieldDidBeginEditing:(UITextField *)textField
{
//    if ([self.delegate respondsToSelector:@selector(searchBarDidBeginEditingTextField:)])
//    {
//        [self.delegate searchBarDidBeginEditingTextField:self];
//    }
}

- (BOOL)textFieldShouldEndEditing:(UITextField *)textField
{
    if ([self.delegate respondsToSelector:@selector(searchBarShouldEndEditingTextField:)])
    {
        [self.delegate searchBarShouldEndEditingTextField:self];
    }
    return YES;
}

- (void)textFieldDidEndEditing:(UITextField *)textField
{
    if ([self.delegate respondsToSelector:@selector(searchBarDidEndEditingTextField:)])
    {
        [self.delegate searchBarDidEndEditingTextField:self];
    }
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    BOOL invalid = YES;
    if ([self.delegate respondsToSelector:@selector(searchBar:invalidInput:)])
    {
        invalid = [self.delegate searchBar:self invalidInput:textField.text];
    }
    if (!invalid)
    {
        textField.text = @"";
        [_alertMessageLabel setHidden:NO];
        [_placeHolder setHidden:YES];
    }
    else
    {
       // [self showCancelButton:YES];
        if ([self.delegate respondsToSelector:@selector(searchBarShouldReturnTextField:)])
        {
            [self.delegate searchBarShouldReturnTextField:self];
        }
    }
    return YES;
}

- (BOOL)textFieldShouldClear:(UITextField *)textField {
    if (self.delegate && [self.delegate respondsToSelector:@selector(searchBarShouldClearTextField:)]) {
        [self.delegate searchBarShouldClearTextField:self];
    }
    return YES;
}

#pragma mark - UITextField observer

- (void)textFieldTextDidChange:(NSNotification*)notif{
    NSLog(@"%@", @(self.maxLength));
    UITextField *textField = (UITextField *)notif.object;
    if (self.maxLength && textField.text.length > self.maxLength) {
        textField.text = [textField.text substringToIndex:self.maxLength];
    }
    
    if (self.delegate && [self.delegate respondsToSelector:@selector(searchBar:textDidChange:)]) {
        [self.delegate searchBar:self textDidChange:_textField.text];
    }
    
    [self textChecking];
}

- (void)textChecking{
    if (_textField.text.length == 0
        || [_textField.text isEqualToString:@""]) {
        [_placeHolder setHidden:!_alertMessageLabel.isHidden];
        
        self.resultCount = -1;//隐藏结果数量label
    }
    else{
        [_placeHolder setHidden:YES];
        [_alertMessageLabel setHidden:YES];
    }
}

- (void)setText:(NSString *)string{
    _textField.text = string;
    [self textChecking];
}

- (NSString*)text{
    return _textField.text;
}

- (void)setPlaceholder:(NSString *)string{
    _placeHolder.text = string;
}

- (NSString*)placeHolder{
    return _placeHolder.text;
}

- (void)setAlertMessage:(NSString*)string{
    _alertMessageLabel.text = string;
}

- (NSString*)alertMessage{
    return _alertMessageLabel.text;
}

- (void)showCancelButton:(BOOL)flag{
    [self showCancelButton:flag animated:YES];
}

- (void)showCancelButton:(BOOL)flag animated:(BOOL)animated
{
    CGRect frame = self.bounds;
    CGRect buttonFrame = _cancelButton.frame;
    
    if (flag) {
        frame.size.width -= (CGRectGetWidth(_cancelButton.frame) + _gap);
    }
    /*else{
     self.text = nil;
     [self textChecking];
     }*/
    
    _textField.clearButtonMode = UITextFieldViewModeNever;
    buttonFrame.origin.x = CGRectGetMaxX(frame) + _gap;
    
    if (animated) {
        [UIView animateWithDuration:0.2 animations:^{
            _searchView.frame = frame;
            _cancelButton.frame = buttonFrame;
            _cancelButton.alpha = flag?1.0f:0.0f;
        } completion:^(BOOL finished) {
            _textField.clearButtonMode = UITextFieldViewModeWhileEditing;
        }];
    }
    else
    {
        _searchView.frame = frame;
        _cancelButton.frame = buttonFrame;
        _cancelButton.alpha = flag?1.0f:0.0f;
        _textField.clearButtonMode = UITextFieldViewModeWhileEditing;
    }
}


- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event{
    
    static NSTimeInterval lastTime = 0;
    static NSInteger count = 0;
    
    NSTimeInterval curTime = [[NSDate date] timeIntervalSince1970];
    
    if (curTime - lastTime < 1) {
        count ++;
    }
    else{
        count = 0;
    }
    
    if (count >= 5) {
        count = 0;
        if (self.delegate && [self.delegate respondsToSelector:@selector(searchBackDoorDidTrigger:)]) {
            [self.delegate searchBackDoorDidTrigger:self];
        }
    }
    
    lastTime = curTime;
}
#pragma mark - 搜索框右侧显示结果数量的label
/** 结果数量label */
-(UILabel *)resultCountLabel
{
    if (!_resultCountLabel) {
        _resultCountLabel = [[UILabel alloc] init];
        _resultCountLabel.font = [UIFont systemFontOfSize:12];
        _resultCountLabel.textAlignment = NSTextAlignmentCenter;
        _resultCountLabel.textColor = [UIColor grayColor];
    }
    
    return _resultCountLabel;
}

/** 设置结果数量 */
- (void)setResultCount:(NSInteger)resultCount
{
    _resultCount = resultCount;
    NSString *numStr = [NSString stringWithFormat:@"%@", @(resultCount)];
    if (resultCount > 99) {
        numStr = @"99+";
    }
    self.resultCountLabel.text = numStr;
    [self displayResultCount];
}

/** 显示结果数量label */
- (void)displayResultCount
{
    if (_resultCount == -1) {
        _textField.rightViewMode = UITextFieldViewModeNever;
        _textField.rightView = nil;
    }
    else
    {
        //需要右侧显示结果数则改为：UITextFieldViewModeUnlessEditing 否则改为 UITextFieldViewModeNever
        _textField.rightViewMode = UITextFieldViewModeUnlessEditing;
        UIFont *font  = self.resultCountLabel.font;
        CGSize size   = CGSizeMake(CGFLOAT_MAX, _textField.frame.size.height);
        
        CGSize textSize = [self.resultCountLabel.text boundingRectWithSize:size options:0 attributes:font == nil ? nil : @{NSFontAttributeName: font} context:nil].size;
        CGFloat width = textSize.width + 2 * _gap;
        CGRect rect   = CGRectMake(_textField.ev_width - width, 0, width, self.ev_height);
        self.resultCountLabel.frame = rect;
        _textField.rightView = self.resultCountLabel;
    }
}

#pragma mark - Public Method
-(void)setButtonTitleColor:(UIColor *)color
{
    [_cancelButton setTitleColor:color forState:UIControlStateNormal];
}

-(void)setButtonBackgroundColor:(UIColor *)color
{
    [_cancelButton setBackgroundColor:color];
}

@end
